
package dao.impl;

import dao.ProveedorDao;
import java.util.List;
import model.Proveedor;
import org.hibernate.Query;
import org.hibernate.Session;
import util.HibernateUtil;


public class ProveedorDaoImpl implements ProveedorDao {

    @Override
    public void insertar(Proveedor proveedor) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            session.save(proveedor);
            session.beginTransaction().commit();
            
        } catch (Exception e) {
            System.out.println("Error al insertar: " + e.getMessage());
            session.beginTransaction().rollback();
            
        }
    }

    @Override
    public void actualizar(Proveedor proveedor) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            session.merge(proveedor);
            session.beginTransaction().commit();
            
        } catch (Exception e) {
            System.out.println("Error al actualizar: " + e.getMessage());
            session.beginTransaction().rollback();
            
        }
    }

    @Override
    public void eliminar(Proveedor proveedor) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            session.delete(proveedor);
            session.beginTransaction().commit();
            
        } catch (Exception e) {
            System.out.println("Error al eliminar: " + e.getMessage());
            session.beginTransaction().rollback();
            
        }
    }

    @Override
    public List<Proveedor> buscarTodos() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        return session.createQuery("from Proveedor").list();
    }

    @Override
    public Proveedor buscarPorId(int id) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        String sql = "select u from Proveedor u where idProveedor=:idproveedor";
        Query query = session.createQuery(sql);
        query.setInteger("idproveedor", id);
        return (Proveedor) query.uniqueResult();
    }
    
    
}
